<?php

/**
 *      [CodeJm!] Author CodeJm[codejm@163.com].
 *
 *
 *      $Id: Wsuser.php 2016-03-31 15:42:44 codejm $
 */
class WxuserModel extends \Core_CMode
{

    public $_table = '`ws_user`';

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => '序号',
            '·subscribe·' => '是否关注该公众号',
            'openid' => '公众号唯一ID',
            '·nickname·' => '用户昵称',
            '·sex·' => '用户的性别，值为1时是男性，值为2时是女性，值为0时是未知',
            'city' => '所在城市',
            '·county·' => '所在国家',
            '·province·' => '所在省份',
            'language' => '用户语言',
            'headimgurl' => '用户头像',
            'subscribe_time' => '关注时间',
            'unionid' => '只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段',
            'remark' => '备注',
            '·groupid·' => '用户所在的分组ID',
            'state' => '状态',
            '·addtime·' => '添加时间',
        );
    }

    /**
     * 楠岃瘉瑙勫垯
     *
     */
    public function rules()
    {
        return array(
            'default' => array(
                array('·subscribe·', 'required|maxlength[1]|integer'),
                array('openid', 'required|maxlength[30]'),
                array('·nickname·', 'required|maxlength[50]'),
                array('·sex·', 'required|maxlength[1]|integer'),
                array('city', 'required|maxlength[50]'),
                array('·county·', 'required|maxlength[50]'),
                array('·province·', 'required|maxlength[50]'),
                array('language', 'required|maxlength[10]'),
                array('headimgurl', 'required|maxlength[200]'),
                array('subscribe_time', 'required|maxlength[20]'),
                array('unionid', 'required|maxlength[50]'),
                array('remark', 'required|maxlength[50]'),
                array('·groupid·', 'required|maxlength[3]|integer'),
                array('state', 'required|maxlength[1]|integer'),
                array('·addtime·', 'required|maxlength[20]'),

            ),
        );
    }

    /**
     * 批量删除
     *
     */
    public function delWsusers($ids)
    {
        $ids_str = implode(',', array_fill(0, count($ids), '?'));
        $where = 'id IN (' . $ids_str . ')';
        return $this->update($where, array('status' => -1), $ids);
    }

    public function recordWxUserInfo($userInfo_obj)
    {
        //获取随机用户名
        $username = $this->generateUserName();
        //数组转字符
        $privilege_str = implode($userInfo_obj->privilege, ',');
        //组织入库前数据
        $data = array(
            'username' => $username,
            'subscribe' => 0,
            'openid' => $userInfo_obj->openid,
            'nickname' => $userInfo_obj->nickname,
            'sex' => $userInfo_obj->sex,
            'province' => $userInfo_obj->province,
            'city' => $userInfo_obj->city,
            'country' => $userInfo_obj->country,
            'headimgurl' => $userInfo_obj->headimgurl,
            'privilege' => $privilege_str,
            'unionid' => $userInfo_obj->unionid,
            'channel' => 'weixin',
            'status' => '1',
            'addtime' => time(),
        );

        //组织字段名字
        $colNames = '';
        $values = '';
        foreach ($data as $k => $v) {
            $colNames .= $k . ',';
            $values .= "'" . $v . "'" . ',';
        }

        //去除多余字符
        $colNames = trim($colNames, ',');
        $values = trim($values, ',');
        //PDO操作
        //SQL
        $sql = 'insert into ' . $this->_table . "($colNames) values($values)";
        //执行sql语句
        $result = $this->db->prepare($sql);
        $result->execute();
        $inserid = $this->db->lastInsertId();
        $result->closeCursor();

        return $inserid;
    }

    public function recordMWxUserinfo($openid, $phonenum)
    {
        //获取随机用户名
        $username = $this->generateUserName();
        //data
        $data = array(
            $username,$openid, $phonenum, 'mobile', 1, time()
        );
        //SQL
        $sql = 'insert into ' . $this->_table . '(username,openid,phonenum,channel,status,addtime) values(?,?,?,?,?,?)';
        $result = $this->db->prepare($sql);
        $result->execute($data);
        $lastid = $this->db->lastInsertId();
        //返回受影响的行数
        return $lastid;
    }

    //检查用户是否已经存在
    public function checkWUserExist($openId)
    {
        //SQL
        $sql = 'select * from ' . $this->_table . ' where openid=:openid';
        $result = $this->db->prepare($sql);
        $result->execute(array('openid' => $openId));
        $data = $result->fetch(PDO::FETCH_ASSOC);
        return $data;
    }

    //检查手机+微信用户是否已经存在
    public function checkMWUserExist($openId, $phoneNum)
    {
        //SQL
        $sql = 'select * from ' . $this->_table . ' where openid=:openid and phonenum=:phonenum';
        $result = $this->db->prepare($sql);
        $result->execute(array('openid' => $openId, 'phonenum' => $phoneNum));
        $data = $result->fetch(PDO::FETCH_ASSOC);
        return $data;
    }

    //检查用户是否已经存在
    public function checkMUserExist($phonenum)
    {
        //SQL
        $sql = 'select * from ' . $this->_table . ' where phonenum=:phonenum';
        $result = $this->db->prepare($sql);
        $result->execute(array('phonenum' => $phonenum));
        $data = $result->fetch(PDO::FETCH_ASSOC);
        return $data;
    }

    //记录手机用户
    public function recordMobileUser($phonenum)
    {
        //data
        $data = array(
            $phonenum, 'mobile', 1, time()
        );
        //SQL
        $sql = 'insert into ' . $this->_table . '(phonenum,channel,status,addtime) values(?,?,?,?)';
        $result = $this->db->prepare($sql);
        $result->execute($data);
        //$row = $result->rowCount();
        $lastid = $this->db->lastInsertId();
        //返回受影响的行数
        return $lastid;
    }

    //记录在线用户信息
    //$type 表示微信 还是手机用户
    public function recodeUserInfo($data, $type = 'weixin', $id = 0)
    {
        //读取原有的用户
        $user_arr = Tools_help::getSession($type . '_user');
        if (empty($user_arr)) {
            //申请数组
            $user_arr = array();
            array_push($user_arr, array($type => $data, 'id' => $id));
        } else {
            //数组不为空
            array_push($user_arr, array($type => $data, 'id' => $id));
        }

        //放进session
        Tools_help::setSession($type . '_user', $user_arr);
    }

    //删除在线用户信息
    //$type 表示微信 还是手机用户
    //$data 表示 openid 或者是 手机号
    public function deleteUserInfo($type = 'weixin', $data)
    {
        //获取要判断的key
        if ($type == 'weixin') {
            $key = 'openid';
        } else {
            $key = 'mobile';
        }

        //读取原有的用户
        $user_arr = Tools_help::getSession($type . '_user');
        //循环遍历
        if ($user_arr) {
            foreach ($user_arr as $k => $user) {
                if ($user[$key] == $data) {
                    //删除特定用户信息
                    unset($user_arr[$k]);
                }
            }
        }
        //放进session
        Tools_help::setSession($type . '_user', $user_arr);
    }

    //通过id找到个人信息
    public function getSessionById($id)
    {
        //读取微信用户
        $user_arr = Tools_help::getSession('weixin' . '_user');
        //循环遍历
        if ($user_arr) {
            foreach ($user_arr as $k => $user) {
                if ($user['id'] == $id) {
                    //返回用户信息
                    return $user_arr[$k];
                }
            }
        }

        //读取手机用户
        $user_arr = Tools_help::getSession('mobile' . '_user');
        //循环遍历
        if ($user_arr) {
            foreach ($user_arr as $k => $user) {
                if ($user['id'] == $id) {
                    //返回用户信息
                    return $user_arr[$k];
                }
            }
        }
        return null;
    }

    //统一删除用户session
    public function deleteAllUserInfo($id)
    {
        //读取微信用户
        $user_arr = Tools_help::getSession('weixin_user');
        //循环遍历
        if ($user_arr) {
            foreach ($user_arr as $k => $user) {
                if ($user['id'] == $id) {
                    //删除特定用户信息
                    unset($user_arr[$k]);
                }
            }
        }
        //放进session
        Tools_help::setSession('weixin_user', $user_arr);

        //读取手机用户
        $user_arr = Tools_help::getSession('mobile_user');
        //循环遍历
        if ($user_arr) {
            foreach ($user_arr as $k => $user) {
                if ($user['id'] == $id) {
                    //删除特定用户信息
                    unset($user_arr[$k]);
                }
            }
        }
        //放进session
        Tools_help::setSession('mobile_user', $user_arr);
    }

    //判断用户是否登录
    public function checkUserIsLogin($id)
    {
        //读取微信用户
        $user_arr = Tools_help::getSession('weixin_user');
        //循环遍历
        if ($user_arr) {
            foreach ($user_arr as $k => $user) {
                if ($user['id'] == $id) {
                    return true;
                }
            }
        }

        //读取手机用户
        $user_arr = Tools_help::getSession('mobile_user');
        //循环遍历
        if ($user_arr) {
            foreach ($user_arr as $k => $user) {
                if ($user['id'] == $id) {
                    return true;
                }
            }
        }
        //没有找到此用户
        return false;
    }

    //为用户名生成随机字符
    public function generateUserName() {
        //获取当前时间
        $time_str = date('Ymd',time());
        //生成6位的随机字符
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < 6; $i++ )  {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        //组合字符
        $username = 'dfqz_' . $time_str . $str;

        return $username;
    }
}

?>
